HIGH LOW just differentSo lets make more fun with discovering trends
here I put high pivot and low pivot and from it we make our lines based on them
look cool:)
"high low" için komut dosyalarını ara
High/Low LabelsThis simple Version 6 script labels each bar on the chart with Green labels noting HH for higher highs and HL for higher lows. And Red labels noting LH for lower highs and LL for lower lows. Works on any Trading View chart and any time frame. Any comments or suggestions, please do!
High/Low X Bars AgoThis indicator will plot a line on your chart that shows the highest high point between two previous points on the chart. It does this by reporting the highest point of X number of candles, and begins the look-back X number of candles ago.
Default candle group size is 50, and default look-back begins 50 candles back.
With these settings, the script will essentially plot the highest high point between the candle that printed 100 candles ago, and the candle that printed 50 candles ago.
Options are available for looking for the highest point, or lowest point, with configurable distances in the look-back and candle group ranges.
This script was custom built by Pine-Labs for a user who requested it.
High Low Markers v1Retrieves the previous day’s high using request.security(...), so it works on any timeframe, even intraday.
Creates a single label (stored in a var variable) at that previous day high.
Places the text on the right of the anchor point by using label.style_label_right.
Updates the label’s position each bar (or only on a new day, if desired) so it always reflects the most recent previous day’s high.
Highs-Lows Bands Trend FollowingTwo bands formed by moving averages of highs and lows.
The lower band should provide zone of support in uptrends while the upper band should provide zone of resistance during downtrends.
Bands that turn green in bullish trends should provide buy signals while bands that turn red in bearish trends should provide sell signals.
High/Low bandsGives good idea about trend.
In last 100 days the lowest price was this.
In last 100 days the highest price was this.
Price makes new 100 days high! (uptrend)
High_Low_ProjectionHigh Low Projections of daily/weekly/quarterly/yearly price movement. Dark/night mode version. Green when broken through to upside, red when broken through to bottom side.
High Low Bollinger Bands Better than Bollinger Bands for finding extreme points timed by an oscillator where the price is statistically likely to stay inside the boundaries.
Good for setting credit spreads such as call and put vertical spreads.
RSI Donchian Channel [DCAUT]█ RSI Donchian Channel
📊 ORIGINALITY & INNOVATION
The RSI Donchian Channel represents an important synthesis of two complementary analytical frameworks: momentum oscillators and breakout detection systems. This indicator addresses a common limitation in traditional RSI analysis by replacing fixed overbought/oversold thresholds with adaptive zones derived from historical RSI extremes.
Key Enhancement:
Traditional RSI analysis relies on static threshold levels (typically 30/70), which may not adequately reflect changing market volatility regimes. This indicator adapts the reference zones dynamically based on the actual RSI behavior over the lookback period, helping traders identify meaningful momentum extremes relative to recent price action rather than arbitrary fixed levels.
The implementation combines the proven momentum measurement capabilities of RSI with Donchian Channel's breakout detection methodology, creating a framework that identifies both momentum exhaustion points and potential continuation signals through the same analytical lens.
📐 MATHEMATICAL FOUNDATION
Core Calculation Process:
Step 1: RSI Calculation
The Relative Strength Index measures momentum by comparing the magnitude of recent gains to recent losses:
Calculate price changes between consecutive periods
Separate positive changes (gains) from negative changes (losses)
Apply selected smoothing method (RMA standard, also supports SMA, EMA, WMA) to both gain and loss series
Compute Relative Strength (RS) as the ratio of smoothed gains to smoothed losses
Transform RS into bounded 0-100 scale using the formula: RSI = 100 - (100 / (1 + RS))
Step 2: Donchian Channel Application
The Donchian Channel identifies the highest and lowest RSI values within the specified lookback period:
Upper Channel: Highest RSI value over the lookback period, represents the recent momentum peak
Lower Channel: Lowest RSI value over the lookback period, represents the recent momentum trough
Middle Channel (Basis): Average of upper and lower channels, serves as equilibrium reference
Channel Width Dynamics:
The distance between upper and lower channels reflects RSI volatility. Wide channels indicate high momentum variability, while narrow channels suggest momentum consolidation and potential breakout preparation. The indicator monitors channel width over a 100-period window to identify squeeze conditions that often precede significant momentum shifts.
📊 COMPREHENSIVE SIGNAL ANALYSIS
Primary Signal Categories:
Breakout Signals:
Upper Breakout: RSI crosses above the upper channel, indicates momentum reaching new relative highs and potential trend continuation, particularly significant when accompanied by price confirmation
Lower Breakout: RSI crosses below the lower channel, suggests momentum reaching new relative lows and potential trend exhaustion or reversal setup
Breakout strength is enhanced when the channel is narrow prior to the breakout, indicating a transition from consolidation to directional movement
Mean Reversion Signals:
Upper Touch Without Breakout: RSI reaches the upper channel but fails to break through, may indicate momentum exhaustion and potential reversal opportunity
Lower Touch Without Breakout: RSI reaches the lower channel without breakdown, suggests potential bounce as momentum reaches oversold extremes
Return to Basis: RSI moving back toward the middle channel after touching extremes signals momentum normalization
Trend Strength Assessment:
Sustained Upper Channel Riding: RSI consistently remains near or above the upper channel during strong uptrends, indicates persistent bullish momentum
Sustained Lower Channel Riding: RSI stays near or below the lower channel during strong downtrends, reflects persistent bearish pressure
Basis Line Position: RSI position relative to the middle channel helps identify the prevailing momentum bias
Channel Compression Patterns:
Squeeze Detection: Channel width narrowing to 100-period lows indicates momentum consolidation, often precedes significant directional moves
Expansion Phase: Channel widening after a squeeze confirms the initiation of a new momentum regime
Persistent Narrow Channels: Extended periods of tight channels suggest market indecision and accumulation/distribution phases
🎯 STRATEGIC APPLICATIONS
Trend Continuation Strategy:
This approach focuses on identifying and trading momentum breakouts that confirm established trends:
Identify the prevailing price trend using higher timeframe analysis or trend-following indicators
Wait for RSI to break above the upper channel in uptrends (or below the lower channel in downtrends)
Enter positions in the direction of the breakout when price action confirms the momentum shift
Place protective stops below the recent swing low (long positions) or above swing high (short positions)
Target profit levels based on prior swing extremes or use trailing stops to capture extended moves
Exit when RSI crosses back through the basis line in the opposite direction
Mean Reversion Strategy:
This method capitalizes on momentum extremes and subsequent corrections toward equilibrium:
Monitor for RSI reaching the upper or lower channel boundaries
Look for rejection signals (price reversal patterns, volume divergence) when RSI touches the channels
Enter counter-trend positions when RSI begins moving back toward the basis line
Use the basis line as the initial profit target for mean reversion trades
Implement tight stops beyond the channel extremes to limit risk on failed reversals
Scale out of positions as RSI approaches the basis line and closes the position when RSI crosses the basis
Breakout Preparation Strategy:
This approach positions traders ahead of potential volatility expansion from consolidation phases:
Identify squeeze conditions when channel width reaches 100-period lows
Monitor price action for consolidation patterns (triangles, rectangles, flags) during the squeeze
Prepare conditional orders for breakouts in both directions from the consolidation
Enter positions when RSI breaks out of the narrow channel with expanding width
Use the channel width expansion as a confirmation signal for the breakout's validity
Manage risk with stops just inside the opposite channel boundary
Multi-Timeframe Confluence Strategy:
Combining RSI Donchian Channel analysis across multiple timeframes can improve signal reliability:
Identify the primary trend direction using a higher timeframe RSI Donchian Channel (e.g., daily or weekly)
Use a lower timeframe (e.g., 4-hour or hourly) to time precise entry points
Enter long positions when both timeframes show RSI above their respective basis lines
Enter short positions when both timeframes show RSI below their respective basis lines
Avoid trades when timeframes provide conflicting signals (e.g., higher timeframe below basis, lower timeframe above)
Exit when the higher timeframe RSI crosses its basis line in the opposite direction
Risk Management Guidelines:
Effective risk management is essential for all RSI Donchian Channel strategies:
Position Sizing: Calculate position sizes based on the distance between entry point and stop loss, limiting risk to 1-2% of capital per trade
Stop Loss Placement: For breakout trades, place stops just inside the opposite channel boundary; for mean reversion trades, use stops beyond the channel extremes
Profit Targets: Use the basis line as a minimum target for mean reversion trades; for trend trades, target prior swing extremes or use trailing stops
Channel Width Context: Increase position sizes during narrow channels (lower volatility) and reduce sizes during wide channels (higher volatility)
Correlation Awareness: Monitor correlations between traded instruments to avoid over-concentration in similar setups
📋 DETAILED PARAMETER CONFIGURATION
RSI Source:
Defines the price data series used for RSI calculation:
Close (Default): Standard choice providing end-of-period momentum assessment, suitable for most trading styles and timeframes
High-Low Average (HL2): Reduces the impact of closing auction dynamics, useful for markets with significant end-of-day volatility
High-Low-Close Average (HLC3): Provides a more balanced view incorporating the entire period's range
Open-High-Low-Close Average (OHLC4): Offers the most comprehensive price representation, helpful for identifying overall period sentiment
Strategy Consideration: Use Close for end-of-period signals, HL2 or HLC3 for intraday volatility reduction, OHLC4 for capturing full period dynamics
RSI Length:
Controls the number of periods used for RSI calculation:
Short Periods (5-9): Highly responsive to recent price changes, produces more frequent signals with increased false signal risk, suitable for short-term trading and volatile markets
Standard Period (14): Widely accepted default balancing responsiveness with stability, appropriate for swing trading and intermediate-term analysis
Long Periods (21-28): Produces smoother RSI with fewer signals but more reliable trend identification, better for position trading and reducing noise in choppy markets
Optimization Approach: Test different lengths against historical data for your specific market and timeframe, consider using longer periods in ranging markets and shorter periods in trending markets
RSI MA Type:
Determines the smoothing method applied to price changes in RSI calculation:
RMA (Relative Moving Average - Default): Wilder's original smoothing method providing stable momentum measurement with gradual response to changes, maintains consistency with classical RSI interpretation
SMA (Simple Moving Average): Treats all periods equally, responds more quickly to changes than RMA but may produce more whipsaws in volatile conditions
EMA (Exponential Moving Average): Weights recent periods more heavily, increases responsiveness at the cost of potential noise, suitable for traders prioritizing early signal generation
WMA (Weighted Moving Average): Applies linear weighting favoring recent data, offers a middle ground between SMA and EMA responsiveness
Selection Guidance: Maintain RMA for consistency with traditional RSI analysis, use EMA or WMA for more responsive signals in fast-moving markets, apply SMA for maximum simplicity and transparency
DC Length:
Specifies the lookback period for Donchian Channel calculation on RSI values:
Short Periods (10-14): Creates tight channels that adapt quickly to changing momentum conditions, generates more frequent trading signals but increases sensitivity to short-term RSI fluctuations
Standard Period (20): Balances channel responsiveness with stability, aligns with traditional Bollinger Bands and moving average periods, suitable for most trading styles
Long Periods (30-50): Produces wider, more stable channels that better represent sustained momentum extremes, reduces signal frequency while improving reliability, appropriate for position traders and higher timeframes
Calibration Strategy: Match DC length to your trading timeframe (shorter for day trading, longer for swing trading), test channel width behavior during different market regimes, consider using adaptive periods that adjust to volatility conditions
Market Adaptation: Use shorter DC lengths in trending markets to capture momentum shifts earlier, apply longer periods in ranging markets to filter noise and focus on significant extremes
Parameter Combination Recommendations:
Scalping/Day Trading: RSI Length 5-9, DC Length 10-14, EMA or WMA smoothing for maximum responsiveness
Swing Trading: RSI Length 14, DC Length 20, RMA smoothing for balanced analysis (default configuration)
Position Trading: RSI Length 21-28, DC Length 30-50, RMA or SMA smoothing for stable signals
High Volatility Markets: Longer RSI periods (21+) with standard DC length (20) to reduce noise
Low Volatility Markets: Standard RSI length (14) with shorter DC length (10-14) to capture subtle momentum shifts
📈 PERFORMANCE ANALYSIS & COMPETITIVE ADVANTAGES
Adaptive Threshold Mechanism:
Unlike traditional RSI analysis with fixed 30/70 thresholds, this indicator's Donchian Channel approach provides several improvements:
Context-Aware Extremes: Overbought/oversold levels adjust automatically based on recent momentum behavior rather than arbitrary fixed values
Volatility Adaptation: In low volatility periods, channels narrow to reflect tighter momentum ranges; in high volatility, channels widen appropriately
Market Regime Recognition: The indicator implicitly adapts to different market conditions without manual threshold adjustments
False Signal Reduction: Adaptive channels help reduce premature reversal signals that often occur with fixed thresholds during strong trends
Signal Quality Characteristics:
The indicator's dual-purpose design provides distinct advantages for different trading objectives:
Breakout Trading: Channel boundaries offer clear, objective breakout levels that update dynamically, eliminating the ambiguity of when momentum becomes "too high" or "too low"
Mean Reversion: The basis line provides a natural profit target for reversion trades, representing the midpoint of recent momentum extremes
Trend Strength: Persistent channel boundary riding offers an objective measure of trend strength without additional indicators
Consolidation Detection: Channel width analysis provides early warning of potential volatility expansion from compression phases
Comparative Analysis:
When compared to traditional RSI implementations and other momentum frameworks:
vs. Fixed Threshold RSI: Provides market-adaptive reference levels rather than static values, helping to reduce false signals during trending markets where RSI can remain "overbought" or "oversold" for extended periods
vs. RSI Bollinger Bands: Offers clearer breakout signals and more intuitive extreme identification through actual high/low boundaries rather than statistical standard deviations
vs. Stochastic Oscillator: Maintains RSI's momentum measurement advantages (unbounded calculation avoiding scale compression) while adding the breakout detection capabilities of Donchian Channels
vs. Standard Donchian Channels: Applies breakout methodology to momentum space rather than price, providing earlier signals of potential trend changes before price breakouts occur
Performance Characteristics:
The indicator exhibits specific behavioral patterns across different market conditions:
Trending Markets: Excels at identifying momentum continuation through channel breakouts, RSI tends to ride one channel boundary during strong trends, providing trend confirmation
Ranging Markets: Channel width narrows during consolidation, offering early preparation signals for potential breakout trading opportunities
High Volatility: Channels widen to reflect increased momentum variability, automatically adjusting signal sensitivity to match market conditions
Low Volatility: Channels contract, making the indicator more sensitive to subtle momentum shifts that may be significant in calm market environments
Transition Periods: Channel squeezes often precede major trend changes, offering advance warning of potential regime shifts
Limitations and Considerations:
Users should be aware of certain operational characteristics:
Lookback Dependency: Channel boundaries depend entirely on the lookback period, meaning the indicator has no predictive element beyond identifying current momentum relative to recent history
Lag Characteristics: As with all moving average-based indicators, RSI calculation introduces lag, and channel boundaries update only as new extremes occur within the lookback window
Range-Bound Sensitivity: In extremely tight ranges, channels may become very narrow, potentially generating excessive signals from minor momentum fluctuations
Trending Persistence: During very strong trends, RSI may remain at channel extremes for extended periods, requiring patience for mean reversion setups or commitment to trend-following approaches
No Absolute Levels: Unlike traditional RSI, this indicator provides no fixed reference points (like 50), making it less suitable for strategies that depend on absolute momentum readings
USAGE NOTES
This indicator is designed for technical analysis and educational purposes to help traders understand momentum dynamics and identify potential trading opportunities. The RSI Donchian Channel has limitations and should not be used as the sole basis for trading decisions.
Important considerations:
Performance varies significantly across different market conditions, timeframes, and instruments
Historical signal patterns do not guarantee future results, as market behavior continuously evolves
Effective use requires understanding of both RSI momentum principles and Donchian Channel breakout concepts
Risk management practices (stop losses, position sizing, diversification) are essential for any trading application
Consider combining with additional analytical tools such as volume analysis, price action patterns, or trend indicators for confirmation
Backtest thoroughly on your specific instruments and timeframes before live trading implementation
Be aware that optimization on historical data may lead to curve-fitting and poor forward performance
The indicator performs best when used as part of a comprehensive trading methodology that incorporates multiple forms of market analysis, sound risk management, and realistic expectations about win rates and drawdowns.
Keltner Channel Enhanced [DCAUT]█ Keltner Channel Enhanced
📊 ORIGINALITY & INNOVATION
The Keltner Channel Enhanced represents an important advancement over standard Keltner Channel implementations by introducing dual flexibility in moving average selection for both the middle band and ATR calculation. While traditional Keltner Channels typically use EMA for the middle band and RMA (Wilder's smoothing) for ATR, this enhanced version provides access to 25+ moving average algorithms for both components, enabling traders to fine-tune the indicator's behavior to match specific market characteristics and trading approaches.
Key Advancements:
Dual MA Algorithm Flexibility: Independent selection of moving average types for middle band (25+ options) and ATR smoothing (25+ options), allowing optimization of both trend identification and volatility measurement separately
Enhanced Trend Sensitivity: Ability to use faster algorithms (HMA, T3) for middle band while maintaining stable volatility measurement with traditional ATR smoothing, or vice versa for different trading strategies
Adaptive Volatility Measurement: Choice of ATR smoothing algorithm affects channel responsiveness to volatility changes, from highly reactive (SMA, EMA) to smoothly adaptive (RMA, TEMA)
Comprehensive Alert System: Five distinct alert conditions covering breakouts, trend changes, and volatility expansion, enabling automated monitoring without constant chart observation
Multi-Timeframe Compatibility: Works effectively across all timeframes from intraday scalping to long-term position trading, with independent optimization of trend and volatility components
This implementation addresses key limitations of standard Keltner Channels: fixed EMA/RMA combination may not suit all market conditions or trading styles. By decoupling the trend component from volatility measurement and allowing independent algorithm selection, traders can create highly customized configurations for specific instruments and market phases.
📐 MATHEMATICAL FOUNDATION
Keltner Channel Enhanced uses a three-component calculation system that combines a flexible moving average middle band with ATR-based (Average True Range) upper and lower channels, creating volatility-adjusted trend-following bands.
Core Calculation Process:
1. Middle Band (Basis) Calculation:
The basis line is calculated using the selected moving average algorithm applied to the price source over the specified period:
basis = ma(source, length, maType)
Supported algorithms include EMA (standard choice, trend-biased), SMA (balanced and symmetric), HMA (reduced lag), WMA, VWMA, TEMA, T3, KAMA, and 17+ others.
2. Average True Range (ATR) Calculation:
ATR measures market volatility by calculating the average of true ranges over the specified period:
trueRange = max(high - low, abs(high - close ), abs(low - close ))
atrValue = ma(trueRange, atrLength, atrMaType)
ATR smoothing algorithm significantly affects channel behavior, with options including RMA (standard, very smooth), SMA (moderate smoothness), EMA (fast adaptation), TEMA (smooth yet responsive), and others.
3. Channel Calculation:
Upper and lower channels are positioned at specified multiples of ATR from the basis:
upperChannel = basis + (multiplier × atrValue)
lowerChannel = basis - (multiplier × atrValue)
Standard multiplier is 2.0, providing channels that dynamically adjust width based on market volatility.
Keltner Channel vs. Bollinger Bands - Key Differences:
While both indicators create volatility-based channels, they use fundamentally different volatility measures:
Keltner Channel (ATR-based):
Uses Average True Range to measure actual price movement volatility
Incorporates gaps and limit moves through true range calculation
More stable in trending markets, less prone to extreme compression
Better reflects intraday volatility and trading range
Typically fewer band touches, making touches more significant
More suitable for trend-following strategies
Bollinger Bands (Standard Deviation-based):
Uses statistical standard deviation to measure price dispersion
Based on closing prices only, doesn't account for intraday range
Can compress significantly during consolidation (squeeze patterns)
More touches in ranging markets
Better suited for mean-reversion strategies
Provides statistical probability framework (95% within 2 standard deviations)
Algorithm Combination Effects:
The interaction between middle band MA type and ATR MA type creates different indicator characteristics:
Trend-Focused Configuration (Fast MA + Slow ATR): Middle band uses HMA/EMA/T3, ATR uses RMA/TEMA, quick trend changes with stable channel width, suitable for trend-following
Volatility-Focused Configuration (Slow MA + Fast ATR): Middle band uses SMA/WMA, ATR uses EMA/SMA, stable trend with dynamic channel width, suitable for volatility trading
Balanced Configuration (Standard EMA/RMA): Classic Keltner Channel behavior, time-tested combination, suitable for general-purpose trend following
Adaptive Configuration (KAMA + KAMA): Self-adjusting indicator responding to efficiency ratio, suitable for markets with varying trend strength and volatility regimes
📊 COMPREHENSIVE SIGNAL ANALYSIS
Keltner Channel Enhanced provides multiple signal categories optimized for trend-following and breakout strategies.
Channel Position Signals:
Upper Channel Interaction:
Price Touching Upper Channel: Strong bullish momentum, price moving more than typical volatility range suggests, potential continuation signal in established uptrends
Price Breaking Above Upper Channel: Exceptional strength, price exceeding normal volatility expectations, consider adding to long positions or tightening trailing stops
Price Riding Upper Channel: Sustained strong uptrend, characteristic of powerful bull moves, stay with trend and avoid premature profit-taking
Price Rejection at Upper Channel: Momentum exhaustion signal, consider profit-taking on longs or waiting for pullback to middle band for reentry
Lower Channel Interaction:
Price Touching Lower Channel: Strong bearish momentum, price moving more than typical volatility range suggests, potential continuation signal in established downtrends
Price Breaking Below Lower Channel: Exceptional weakness, price exceeding normal volatility expectations, consider adding to short positions or protecting against further downside
Price Riding Lower Channel: Sustained strong downtrend, characteristic of powerful bear moves, stay with trend and avoid premature covering
Price Rejection at Lower Channel: Momentum exhaustion signal, consider covering shorts or waiting for bounce to middle band for reentry
Middle Band (Basis) Signals:
Trend Direction Confirmation:
Price Above Basis: Bullish trend bias, middle band acts as dynamic support in uptrends, consider long positions or holding existing longs
Price Below Basis: Bearish trend bias, middle band acts as dynamic resistance in downtrends, consider short positions or avoiding longs
Price Crossing Above Basis: Potential trend change from bearish to bullish, early signal to establish long positions
Price Crossing Below Basis: Potential trend change from bullish to bearish, early signal to establish short positions or exit longs
Pullback Trading Strategy:
Uptrend Pullback: Price pulls back from upper channel to middle band, finds support, and resumes upward, ideal long entry point
Downtrend Bounce: Price bounces from lower channel to middle band, meets resistance, and resumes downward, ideal short entry point
Basis Test: Strong trends often show price respecting the middle band as support/resistance on pullbacks
Failed Test: Price breaking through middle band against trend direction signals potential reversal
Volatility-Based Signals:
Narrow Channels (Low Volatility):
Consolidation Phase: Channels contract during periods of reduced volatility and directionless price action
Breakout Preparation: Narrow channels often precede significant directional moves as volatility cycles
Trading Approach: Reduce position sizes, wait for breakout confirmation, avoid range-bound strategies within channels
Breakout Direction: Monitor for price breaking decisively outside channel range with expanding width
Wide Channels (High Volatility):
Trending Phase: Channels expand during strong directional moves and increased volatility
Momentum Confirmation: Wide channels confirm genuine trend with substantial volatility backing
Trading Approach: Trend-following strategies excel, wider stops necessary, mean-reversion strategies risky
Exhaustion Signs: Extreme channel width (historical highs) may signal approaching consolidation or reversal
Advanced Pattern Recognition:
Channel Walking Pattern:
Upper Channel Walk: Price consistently touches or exceeds upper channel while staying above basis, very strong uptrend signal, hold longs aggressively
Lower Channel Walk: Price consistently touches or exceeds lower channel while staying below basis, very strong downtrend signal, hold shorts aggressively
Basis Support/Resistance: During channel walks, price typically uses middle band as support/resistance on minor pullbacks
Pattern Break: Price crossing basis during channel walk signals potential trend exhaustion
Squeeze and Release Pattern:
Squeeze Phase: Channels narrow significantly, price consolidates near middle band, volatility contracts
Direction Clues: Watch for price positioning relative to basis during squeeze (above = bullish bias, below = bearish bias)
Release Trigger: Price breaking outside narrow channel range with expanding width confirms breakout
Follow-Through: Measure squeeze height and project from breakout point for initial profit targets
Channel Expansion Pattern:
Breakout Confirmation: Rapid channel widening confirms volatility increase and genuine trend establishment
Entry Timing: Enter positions early in expansion phase before trend becomes overextended
Risk Management: Use channel width to size stops appropriately, wider channels require wider stops
Basis Bounce Pattern:
Clean Bounce: Price touches middle band and immediately reverses, confirms trend strength and entry opportunity
Multiple Bounces: Repeated basis bounces indicate strong, sustainable trend
Bounce Failure: Price penetrating basis signals weakening trend and potential reversal
Divergence Analysis:
Price/Channel Divergence: Price makes new high/low while staying within channel (not reaching outer band), suggests momentum weakening
Width/Price Divergence: Price breaks to new extremes but channel width contracts, suggests move lacks conviction
Reversal Signal: Divergences often precede trend reversals or significant consolidation periods
Multi-Timeframe Analysis:
Keltner Channels work particularly well in multi-timeframe trend-following approaches:
Three-Timeframe Alignment:
Higher Timeframe (Weekly/Daily): Identify major trend direction, note price position relative to basis and channels
Intermediate Timeframe (Daily/4H): Identify pullback opportunities within higher timeframe trend
Lower Timeframe (4H/1H): Time precise entries when price touches middle band or lower channel (in uptrends) with rejection
Optimal Entry Conditions:
Best Long Entries: Higher timeframe in uptrend (price above basis), intermediate timeframe pulls back to basis, lower timeframe shows rejection at middle band or lower channel
Best Short Entries: Higher timeframe in downtrend (price below basis), intermediate timeframe bounces to basis, lower timeframe shows rejection at middle band or upper channel
Risk Management: Use higher timeframe channel width to set position sizing, stops below/above higher timeframe channels
🎯 STRATEGIC APPLICATIONS
Keltner Channel Enhanced excels in trend-following and breakout strategies across different market conditions.
Trend Following Strategy:
Setup Requirements:
Identify established trend with price consistently on one side of basis line
Wait for pullback to middle band (basis) or brief penetration through it
Confirm trend resumption with price rejection at basis and move back toward outer channel
Enter in trend direction with stop beyond basis line
Entry Rules:
Uptrend Entry:
Price pulls back from upper channel to middle band, shows support at basis (bullish candlestick, momentum divergence)
Enter long on rejection/bounce from basis with stop 1-2 ATR below basis
Aggressive: Enter on first touch; Conservative: Wait for confirmation candle
Downtrend Entry:
Price bounces from lower channel to middle band, shows resistance at basis (bearish candlestick, momentum divergence)
Enter short on rejection/reversal from basis with stop 1-2 ATR above basis
Aggressive: Enter on first touch; Conservative: Wait for confirmation candle
Trend Management:
Trailing Stop: Use basis line as dynamic trailing stop, exit if price closes beyond basis against position
Profit Taking: Take partial profits at opposite channel, move stops to basis
Position Additions: Add to winners on subsequent basis bounces if trend intact
Breakout Strategy:
Setup Requirements:
Identify consolidation period with contracting channel width
Monitor price action near middle band with reduced volatility
Wait for decisive breakout beyond channel range with expanding width
Enter in breakout direction after confirmation
Breakout Confirmation:
Price breaks clearly outside channel (upper for longs, lower for shorts), channel width begins expanding from contracted state
Volume increases significantly on breakout (if using volume analysis)
Price sustains outside channel for multiple bars without immediate reversal
Entry Approaches:
Aggressive: Enter on initial break with stop at opposite channel or basis, use smaller position size
Conservative: Wait for pullback to broken channel level, enter on rejection and resumption, tighter stop
Volatility-Based Position Sizing:
Adjust position sizing based on channel width (ATR-based volatility):
Wide Channels (High ATR): Reduce position size as stops must be wider, calculate position size using ATR-based risk calculation: Risk / (Stop Distance in ATR × ATR Value)
Narrow Channels (Low ATR): Increase position size as stops can be tighter, be cautious of impending volatility expansion
ATR-Based Risk Management: Use ATR-based risk calculations, position size = 0.01 × Capital / (2 × ATR), use multiples of ATR (1-2 ATR) for adaptive stops
Algorithm Selection Guidelines:
Different market conditions benefit from different algorithm combinations:
Strong Trending Markets: Middle band use EMA or HMA, ATR use RMA, capture trends quickly while maintaining stable channel width
Choppy/Ranging Markets: Middle band use SMA or WMA, ATR use SMA or WMA, avoid false trend signals while identifying genuine reversals
Volatile Markets: Middle band and ATR both use KAMA or FRAMA, self-adjusting to changing market conditions reduces manual optimization
Breakout Trading: Middle band use SMA, ATR use EMA or SMA, stable trend with dynamic channels highlights volatility expansion early
Scalping/Day Trading: Middle band use HMA or T3, ATR use EMA or TEMA, both components respond quickly
Position Trading: Middle band use EMA/TEMA/T3, ATR use RMA or TEMA, filter out noise for long-term trend-following
📋 DETAILED PARAMETER CONFIGURATION
Understanding and optimizing parameters is essential for adapting Keltner Channel Enhanced to specific trading approaches.
Source Parameter:
Close (Most Common): Uses closing price, reflects daily settlement, best for end-of-day analysis and position trading, standard choice
HL2 (Median Price): Smooths out closing bias, better represents full daily range in volatile markets, good for swing trading
HLC3 (Typical Price): Gives more weight to close while including full range, popular for intraday applications, slightly more responsive than HL2
OHLC4 (Average Price): Most comprehensive price representation, smoothest option, good for gap-prone markets or highly volatile instruments
Length Parameter:
Controls the lookback period for middle band (basis) calculation:
Short Periods (10-15): Very responsive to price changes, suitable for day trading and scalping, higher false signal rate
Standard Period (20 - Default): Represents approximately one month of trading, good balance between responsiveness and stability, suitable for swing and position trading
Medium Periods (30-50): Smoother trend identification, fewer false signals, better for position trading and longer holding periods
Long Periods (50+): Very smooth, identifies major trends only, minimal false signals but significant lag, suitable for long-term investment
Optimization by Timeframe: 1-15 minute charts use 10-20 period, 30-60 minute charts use 20-30 period, 4-hour to daily charts use 20-40 period, weekly charts use 20-30 weeks.
ATR Length Parameter:
Controls the lookback period for Average True Range calculation, affecting channel width:
Short ATR Periods (5-10): Very responsive to recent volatility changes, standard is 10 (Keltner's original specification), may be too reactive in whipsaw conditions
Standard ATR Period (10 - Default): Chester Keltner's original specification, good balance between responsiveness and stability, most widely used
Medium ATR Periods (14-20): Smoother channel width, ATR 14 aligns with Wilder's original ATR specification, good for position trading
Long ATR Periods (20+): Very smooth channel width, suitable for long-term trend-following
Length vs. ATR Length Relationship: Equal values (20/20) provide balanced responsiveness, longer ATR (20/14) gives more stable channel width, shorter ATR (20/10) is standard configuration, much shorter ATR (20/5) creates very dynamic channels.
Multiplier Parameter:
Controls channel width by setting ATR multiples:
Lower Values (1.0-1.5): Tighter channels with frequent price touches, more trading signals, higher false signal rate, better for range-bound and mean-reversion strategies
Standard Value (2.0 - Default): Chester Keltner's recommended setting, good balance between signal frequency and reliability, suitable for both trending and ranging strategies
Higher Values (2.5-3.0): Wider channels with less frequent touches, fewer but potentially higher-quality signals, better for strong trending markets
Market-Specific Optimization: High volatility markets (crypto, small-caps) use 2.5-3.0 multiplier, medium volatility markets (major forex, large-caps) use 2.0 multiplier, low volatility markets (bonds, utilities) use 1.5-2.0 multiplier.
MA Type Parameter (Middle Band):
Critical selection that determines trend identification characteristics:
EMA (Exponential Moving Average - Default): Standard Keltner Channel choice, Chester Keltner's original specification, emphasizes recent prices, faster response to trend changes, suitable for all timeframes
SMA (Simple Moving Average): Equal weighting of all data points, no directional bias, slower than EMA, better for ranging markets and mean-reversion
HMA (Hull Moving Average): Minimal lag with smooth output, excellent for fast trend identification, best for day trading and scalping
TEMA (Triple Exponential Moving Average): Advanced smoothing with reduced lag, responsive to trends while filtering noise, suitable for volatile markets
T3 (Tillson T3): Very smooth with minimal lag, excellent for established trend identification, suitable for position trading
KAMA (Kaufman Adaptive Moving Average): Automatically adjusts speed based on market efficiency, slow in ranging markets, fast in trends, suitable for markets with varying conditions
ATR MA Type Parameter:
Determines how Average True Range is smoothed, affecting channel width stability:
RMA (Wilder's Smoothing - Default): J. Welles Wilder's original ATR smoothing method, very smooth, slow to adapt to volatility changes, provides stable channel width
SMA (Simple Moving Average): Equal weighting, moderate smoothness, faster response to volatility changes than RMA, more dynamic channel width
EMA (Exponential Moving Average): Emphasizes recent volatility, quick adaptation to new volatility regimes, very responsive channel width changes
TEMA (Triple Exponential Moving Average): Smooth yet responsive, good balance for varying volatility, suitable for most trading styles
Parameter Combination Strategies:
Conservative Trend-Following: Length 30/ATR Length 20/Multiplier 2.5, MA Type EMA or TEMA/ATR MA Type RMA, smooth trend with stable wide channels, suitable for position trading
Standard Balanced Approach: Length 20/ATR Length 10/Multiplier 2.0, MA Type EMA/ATR MA Type RMA, classic Keltner Channel configuration, suitable for general purpose swing trading
Aggressive Day Trading: Length 10-15/ATR Length 5-7/Multiplier 1.5-2.0, MA Type HMA or EMA/ATR MA Type EMA or SMA, fast trend with dynamic channels, suitable for scalping and day trading
Breakout Specialist: Length 20-30/ATR Length 5-10/Multiplier 2.0, MA Type SMA or WMA/ATR MA Type EMA or SMA, stable trend with responsive channel width
Adaptive All-Conditions: Length 20/ATR Length 10/Multiplier 2.0, MA Type KAMA or FRAMA/ATR MA Type KAMA or TEMA, self-adjusting to market conditions
Offset Parameter:
Controls horizontal positioning of channels on chart. Positive values shift channels to the right (future) for visual projection, negative values shift left (past) for historical analysis, zero (default) aligns with current price bars for real-time signal analysis. Offset affects only visual display, not alert conditions or actual calculations.
📈 PERFORMANCE ANALYSIS & COMPETITIVE ADVANTAGES
Keltner Channel Enhanced provides improvements over standard implementations while maintaining proven effectiveness.
Response Characteristics:
Standard EMA/RMA Configuration: Moderate trend lag (approximately 0.4 × length periods), smooth and stable channel width from RMA smoothing, good balance for most market conditions
Fast HMA/EMA Configuration: Approximately 60% reduction in trend lag compared to EMA, responsive channel width from EMA ATR smoothing, suitable for quick trend changes and breakouts
Adaptive KAMA/KAMA Configuration: Variable lag based on market efficiency, automatic adjustment to trending vs. ranging conditions, self-optimizing behavior reduces manual intervention
Comparison with Traditional Keltner Channels:
Enhanced Version Advantages:
Dual Algorithm Flexibility: Independent MA selection for trend and volatility vs. fixed EMA/RMA, separate tuning of trend responsiveness and channel stability
Market Adaptation: Choose configurations optimized for specific instruments and conditions, customize for scalping, swing, or position trading preferences
Comprehensive Alerts: Enhanced alert system including channel expansion detection
Traditional Version Advantages:
Simplicity: Fewer parameters, easier to understand and implement
Standardization: Fixed EMA/RMA combination ensures consistency across users
Research Base: Decades of backtesting and research on standard configuration
When to Use Enhanced Version: Trading multiple instruments with different characteristics, switching between trending and ranging markets, employing different strategies, algorithm-based trading systems requiring customization, seeking optimization for specific trading style and timeframe.
When to Use Standard Version: Beginning traders learning Keltner Channel concepts, following published research or trading systems, preferring simplicity and standardization, wanting to avoid optimization and curve-fitting risks.
Performance Across Market Conditions:
Strong Trending Markets: EMA or HMA basis with RMA or TEMA ATR smoothing provides quicker trend identification, pullbacks to basis offer excellent entry opportunities
Choppy/Ranging Markets: SMA or WMA basis with RMA ATR smoothing and lower multipliers, channel bounce strategies work well, avoid false breakouts
Volatile Markets: KAMA or FRAMA with EMA or TEMA, adaptive algorithms excel by automatic adjustment, wider multipliers (2.5-3.0) accommodate large price swings
Low Volatility/Consolidation: Channels narrow significantly indicating consolidation, algorithm choice less impactful, focus on detecting channel width contraction for breakout preparation
Keltner Channel vs. Bollinger Bands - Usage Comparison:
Favor Keltner Channels When: Trend-following is primary strategy, trading volatile instruments with gaps, want ATR-based volatility measurement, prefer fewer higher-quality channel touches, seeking stable channel width during trends.
Favor Bollinger Bands When: Mean-reversion is primary strategy, trading instruments with limited gaps, want statistical framework based on standard deviation, need squeeze patterns for breakout identification, prefer more frequent trading opportunities.
Use Both Together: Bollinger Band squeeze + Keltner Channel breakout is powerful combination, price outside Bollinger Bands but inside Keltner Channels indicates moderate signal, price outside both indicates very strong signal, Bollinger Bands for entries and Keltner Channels for trend confirmation.
Limitations and Considerations:
General Limitations:
Lagging Indicator: All moving averages lag price, even with reduced-lag algorithms
Trend-Dependent: Works best in trending markets, less effective in choppy conditions
No Direction Prediction: Indicates volatility and deviation, not future direction, requires confirmation
Enhanced Version Specific Considerations:
Optimization Risk: More parameters increase risk of curve-fitting historical data
Complexity: Additional choices may overwhelm beginning traders
Backtesting Challenges: Different algorithms produce different historical results
Mitigation Strategies:
Use Confirmation: Combine with momentum indicators (RSI, MACD), volume, or price action
Test Parameter Robustness: Ensure parameters work across range of values, not just optimized ones
Multi-Timeframe Analysis: Confirm signals across different timeframes
Proper Risk Management: Use appropriate position sizing and stops
Start Simple: Begin with standard EMA/RMA before exploring alternatives
Optimal Usage Recommendations:
For Maximum Effectiveness:
Start with standard EMA/RMA configuration to understand classic behavior
Experiment with alternatives on demo account or paper trading
Match algorithm combination to market condition and trading style
Use channel width analysis to identify market phases
Combine with complementary indicators for confirmation
Implement strict risk management using ATR-based position sizing
Focus on high-quality setups rather than trading every signal
Respect the trend: trade with basis direction for higher probability
Complementary Indicators:
RSI or Stochastic: Confirm momentum at channel extremes
MACD: Confirm trend direction and momentum shifts
Volume: Validate breakouts and trend strength
ADX: Measure trend strength, avoid Keltner signals in weak trends
Support/Resistance: Combine with traditional levels for high-probability setups
Bollinger Bands: Use together for enhanced breakout and volatility analysis
USAGE NOTES
This indicator is designed for technical analysis and educational purposes. Keltner Channel Enhanced has limitations and should not be used as the sole basis for trading decisions. While the flexible moving average selection for both trend and volatility components provides valuable adaptability across different market conditions, algorithm performance varies with market conditions, and past characteristics do not guarantee future results.
Key considerations:
Always use multiple forms of analysis and confirmation before entering trades
Backtest any parameter combination thoroughly before live trading
Be aware that optimization can lead to curve-fitting if not done carefully
Start with standard EMA/RMA settings and adjust only when specific conditions warrant
Understand that no moving average algorithm can eliminate lag entirely
Consider market regime (trending, ranging, volatile) when selecting parameters
Use ATR-based position sizing and risk management on every trade
Keltner Channels work best in trending markets, less effective in choppy conditions
Respect the trend direction indicated by price position relative to basis line
The enhanced flexibility of dual algorithm selection provides powerful tools for adaptation but requires responsible use, thorough understanding of how different algorithms behave under various market conditions, and disciplined risk management.
Trading IQ - ICT LibraryLibrary "ICTlibrary"
Used to calculate various ICT related price levels and strategies. An ongoing project.
Hello Coders!
This library is meant for sourcing ICT related concepts. While some functions might generate more output than you require, you can specify "Lite Mode" as "true" in applicable functions to slim down necessary inputs.
isLastBar(userTF)
Identifies the last bar on the chart before a timeframe change
Parameters:
userTF (simple int) : the timeframe you wish to calculate the last bar for, must be converted to integer using 'timeframe.in_seconds()'
Returns: bool true if bar on chart is last bar of higher TF, dalse if bar on chart is not last bar of higher TF
necessaryData(atrTF)
returns necessaryData UDT for historical data access
Parameters:
atrTF (float) : user-selected timeframe ATR value.
Returns: logZ. log return Z score, used for calculating order blocks.
method gradBoxes(gradientBoxes, idColor, timeStart, bottom, top, rightCoordinate)
creates neon like effect for box drawings
Namespace types: array
Parameters:
gradientBoxes (array) : an array.new() to store the gradient boxes
idColor (color)
timeStart (int) : left point of box
bottom (float) : bottom of box price point
top (float) : top of box price point
rightCoordinate (int) : right point of box
Returns: void
checkIfTraded(tradeName)
checks if recent trade is of specific name
Parameters:
tradeName (string)
Returns: bool true if recent trade id matches target name, false otherwise
checkIfClosed(tradeName)
checks if recent closed trade is of specific name
Parameters:
tradeName (string)
Returns: bool true if recent closed trade id matches target name, false otherwise
IQZZ(atrMult, finalTF)
custom ZZ to quickly determine market direction.
Parameters:
atrMult (float) : an atr multiplier used to determine the required price move for a ZZ direction change
finalTF (string) : the timeframe used for the atr calcuation
Returns: dir market direction. Up => 1, down => -1
method drawBos(id, startPoint, getKeyPointTime, getKeyPointPrice, col, showBOS, isUp)
calculates and draws Break Of Structure
Namespace types: array
Parameters:
id (array)
startPoint (chart.point)
getKeyPointTime (int) : the actual time of startPoint, simplystartPoint.time
getKeyPointPrice (float) : the actual time of startPoint, simplystartPoint.price
col (color) : color of the BoS line / label
showBOS (bool) : whether to show label/line. This function still calculates internally for other ICT related concepts even if not drawn.
isUp (bool) : whether BoS happened during price increase or price decrease.
Returns: void
method drawMSS(id, startPoint, getKeyPointTime, getKeyPointPrice, col, showMSS, isUp, upRejections, dnRejections, highArr, lowArr, timeArr, closeArr, openArr, atrTFarr, upRejectionsPrices, dnRejectionsPrices)
calculates and draws Market Structure Shift. This data is also used to calculate Rejection Blocks.
Namespace types: array
Parameters:
id (array)
startPoint (chart.point)
getKeyPointTime (int) : the actual time of startPoint, simplystartPoint.time
getKeyPointPrice (float) : the actual time of startPoint, simplystartPoint.price
col (color) : color of the MSS line / label
showMSS (bool) : whether to show label/line. This function still calculates internally for other ICT related concepts even if not drawn.
isUp (bool) : whether MSS happened during price increase or price decrease.
upRejections (array)
dnRejections (array)
highArr (array) : array containing historical highs, should be taken from the UDT "necessaryData" defined above
lowArr (array) : array containing historical lows, should be taken from the UDT "necessaryData" defined above
timeArr (array) : array containing historical times, should be taken from the UDT "necessaryData" defined above
closeArr (array) : array containing historical closes, should be taken from the UDT "necessaryData" defined above
openArr (array) : array containing historical opens, should be taken from the UDT "necessaryData" defined above
atrTFarr (array) : array containing historical atr values (of user-selected TF), should be taken from the UDT "necessaryData" defined above
upRejectionsPrices (array) : array containing up rejections prices. Is sorted and used to determine selective looping for invalidations.
dnRejectionsPrices (array) : array containing down rejections prices. Is sorted and used to determine selective looping for invalidations.
Returns: void
method getTime(id, compare, timeArr)
gets time of inputted price (compare) in an array of data
this is useful when the user-selected timeframe for ICT concepts is greater than the chart's timeframe
Namespace types: array
Parameters:
id (array) : the array of data to search through, to find which index has the same value as "compare"
compare (float) : the target data point to find in the array
timeArr (array) : array of historical times
Returns: the time that the data point in the array was recorded
method OB(id, highArr, signArr, lowArr, timeArr, sign)
store bullish orderblock data
Namespace types: array
Parameters:
id (array)
highArr (array) : array of historical highs
signArr (array) : array of historical price direction "math.sign(close - open)"
lowArr (array) : array of historical lows
timeArr (array) : array of historical times
sign (int) : orderblock direction, -1 => bullish, 1 => bearish
Returns: void
OTEstrat(OTEstart, future, closeArr, highArr, lowArr, timeArr, longOTEPT, longOTESL, longOTElevel, shortOTEPT, shortOTESL, shortOTElevel, structureDirection, oteLongs, atrTF, oteShorts)
executes the OTE strategy
Parameters:
OTEstart (chart.point)
future (int) : future time point for drawings
closeArr (array) : array of historical closes
highArr (array) : array of historical highs
lowArr (array) : array of historical lows
timeArr (array) : array of historical times
longOTEPT (string) : user-selected long OTE profit target, please create an input.string() for this using the example below
longOTESL (int) : user-selected long OTE stop loss, please create an input.string() for this using the example below
longOTElevel (float) : long entry price of selected retracement ratio for OTE
shortOTEPT (string) : user-selected short OTE profit target, please create an input.string() for this using the example below
shortOTESL (int) : user-selected short OTE stop loss, please create an input.string() for this using the example below
shortOTElevel (float) : short entry price of selected retracement ratio for OTE
structureDirection (string) : current market structure direction, this should be "Up" or "Down". This is used to cancel pending orders if market structure changes
oteLongs (bool) : input.bool() for whether OTE longs can be executed
atrTF (float) : atr of the user-seleceted TF
oteShorts (bool) : input.bool() for whether OTE shorts can be executed
@exampleInputs
oteLongs = input.bool(defval = false, title = "OTE Longs", group = "Optimal Trade Entry")
longOTElevel = input.float(defval = 0.79, title = "Long Entry Retracement Level", options = , group = "Optimal Trade Entry")
longOTEPT = input.string(defval = "-0.5", title = "Long TP", options = , group = "Optimal Trade Entry")
longOTESL = input.int(defval = 0, title = "How Many Ticks Below Swing Low For Stop Loss", group = "Optimal Trade Entry")
oteShorts = input.bool(defval = false, title = "OTE Shorts", group = "Optimal Trade Entry")
shortOTElevel = input.float(defval = 0.79, title = "Short Entry Retracement Level", options = , group = "Optimal Trade Entry")
shortOTEPT = input.string(defval = "-0.5", title = "Short TP", options = , group = "Optimal Trade Entry")
shortOTESL = input.int(defval = 0, title = "How Many Ticks Above Swing Low For Stop Loss", group = "Optimal Trade Entry")
Returns: void (0)
displacement(logZ, atrTFreg, highArr, timeArr, lowArr, upDispShow, dnDispShow, masterCoords, labelLevels, dispUpcol, rightCoordinate, dispDncol, noBorders)
calculates and draws dispacements
Parameters:
logZ (float) : log return of current price, used to determine a "significant price move" for a displacement
atrTFreg (float) : atr of user-seleceted timeframe
highArr (array) : array of historical highs
timeArr (array) : array of historical times
lowArr (array) : array of historical lows
upDispShow (int) : amount of historical upside displacements to show
dnDispShow (int) : amount of historical downside displacements to show
masterCoords (map) : a map to push the most recent displacement prices into, useful for having key levels in one data structure
labelLevels (string) : used to determine label placement for the displacement, can be inside box, outside box, or none, example below
dispUpcol (color) : upside displacement color
rightCoordinate (int) : future time for displacement drawing, best is "last_bar_time"
dispDncol (color) : downside displacement color
noBorders (bool) : input.bool() to remove box borders, example below
@exampleInputs
labelLevels = input.string(defval = "Inside" , title = "Box Label Placement", options = )
noBorders = input.bool(defval = false, title = "No Borders On Levels")
Returns: void
method getStrongLow(id, startIndex, timeArr, lowArr, strongLowPoints)
unshift strong low data to array id
Namespace types: array
Parameters:
id (array)
startIndex (int) : the starting index for the timeArr array of the UDT "necessaryData".
this point should start from at least 1 pivot prior to find the low before an upside BoS
timeArr (array) : array of historical times
lowArr (array) : array of historical lows
strongLowPoints (array) : array of strong low prices. Used to retrieve highest strong low price and see if need for
removal of invalidated strong lows
Returns: void
method getStrongHigh(id, startIndex, timeArr, highArr, strongHighPoints)
unshift strong high data to array id
Namespace types: array
Parameters:
id (array)
startIndex (int) : the starting index for the timeArr array of the UDT "necessaryData".
this point should start from at least 1 pivot prior to find the high before a downside BoS
timeArr (array) : array of historical times
highArr (array) : array of historical highs
strongHighPoints (array)
Returns: void
equalLevels(highArr, lowArr, timeArr, rightCoordinate, equalHighsCol, equalLowsCol, liteMode)
used to calculate recent equal highs or equal lows
Parameters:
highArr (array) : array of historical highs
lowArr (array) : array of historical lows
timeArr (array) : array of historical times
rightCoordinate (int) : a future time (right for boxes, x2 for lines)
equalHighsCol (color) : user-selected color for equal highs drawings
equalLowsCol (color) : user-selected color for equal lows drawings
liteMode (bool) : optional for a lite mode version of an ICT strategy. For more control over drawings leave as "True", "False" will apply neon effects
Returns: void
quickTime(timeString)
used to quickly determine if a user-inputted time range is currently active in NYT time
Parameters:
timeString (string) : a time range
Returns: true if session is active, false if session is inactive
macros(showMacros, noBorders)
used to calculate and draw session macros
Parameters:
showMacros (bool) : an input.bool() or simple bool to determine whether to activate the function
noBorders (bool) : an input.bool() to determine whether the box anchored to the session should have borders
Returns: void
po3(tf, left, right, show)
use to calculate HTF po3 candle
@tip only call this function on "barstate.islast"
Parameters:
tf (simple string)
left (int) : the left point of the candle, calculated as bar_index + left,
right (int) : :the right point of the candle, calculated as bar_index + right,
show (bool) : input.bool() whether to show the po3 candle or not
Returns: void
silverBullet(silverBulletStratLong, silverBulletStratShort, future, userTF, H, L, H2, L2, noBorders, silverBulletLongTP, historicalPoints, historicalData, silverBulletLongSL, silverBulletShortTP, silverBulletShortSL)
used to execute the Silver Bullet Strategy
Parameters:
silverBulletStratLong (simple bool)
silverBulletStratShort (simple bool)
future (int) : a future time, used for drawings, example "last_bar_time"
userTF (simple int)
H (float) : the high price of the user-selected TF
L (float) : the low price of the user-selected TF
H2 (float) : the high price of the user-selected TF
L2 (float) : the low price of the user-selected TF
noBorders (bool) : an input.bool() used to remove the borders from box drawings
silverBulletLongTP (series silverBulletLevels)
historicalPoints (array)
historicalData (necessaryData)
silverBulletLongSL (series silverBulletLevels)
silverBulletShortTP (series silverBulletLevels)
silverBulletShortSL (series silverBulletLevels)
Returns: void
method invalidFVGcheck(FVGarr, upFVGpricesSorted, dnFVGpricesSorted)
check if existing FVGs are still valid
Namespace types: array
Parameters:
FVGarr (array)
upFVGpricesSorted (array) : an array of bullish FVG prices, used to selective search through FVG array to remove invalidated levels
dnFVGpricesSorted (array) : an array of bearish FVG prices, used to selective search through FVG array to remove invalidated levels
Returns: void (0)
method drawFVG(counter, FVGshow, FVGname, FVGcol, data, masterCoords, labelLevels, borderTransp, liteMode, rightCoordinate)
draws FVGs on last bar
Namespace types: map
Parameters:
counter (map) : a counter, as map, keeping count of the number of FVGs drawn, makes sure that there aren't more FVGs drawn
than int FVGshow
FVGshow (int) : the number of FVGs to show. There should be a bullish FVG show and bearish FVG show. This function "drawFVG" is used separately
for bearish FVG and bullish FVG.
FVGname (string) : the name of the FVG, "FVG Up" or "FVG Down"
FVGcol (color) : desired FVG color
data (FVG)
masterCoords (map) : a map containing the names and price points of key levels. Used to define price ranges.
labelLevels (string) : an input.string with options "Inside", "Outside", "Remove". Determines whether FVG labels should be inside box, outside,
or na.
borderTransp (int)
liteMode (bool)
rightCoordinate (int) : the right coordinate of any drawings. Must be a time point.
Returns: void
invalidBlockCheck(bullishOBbox, bearishOBbox, userTF)
check if existing order blocks are still valid
Parameters:
bullishOBbox (array) : an array declared using the UDT orderBlock that contains bullish order block related data
bearishOBbox (array) : an array declared using the UDT orderBlock that contains bearish order block related data
userTF (simple int)
Returns: void (0)
method lastBarRejections(id, rejectionColor, idShow, rejectionString, labelLevels, borderTransp, liteMode, rightCoordinate, masterCoords)
draws rejectionBlocks on last bar
Namespace types: array
Parameters:
id (array) : the array, an array of rejection block data declared using the UDT rejection block
rejectionColor (color) : the desired color of the rejection box
idShow (int)
rejectionString (string) : the desired name of the rejection blocks
labelLevels (string) : an input.string() to determine if labels for the block should be inside the box, outside, or none.
borderTransp (int)
liteMode (bool) : an input.bool(). True = neon effect, false = no neon.
rightCoordinate (int) : atime for the right coordinate of the box
masterCoords (map) : a map that stores the price of key levels and assigns them a name, used to determine price ranges
Returns: void
method OBdraw(id, OBshow, BBshow, OBcol, BBcol, bullishString, bearishString, isBullish, labelLevels, borderTransp, liteMode, rightCoordinate, masterCoords)
draws orderblocks and breaker blocks for data stored in UDT array()
Namespace types: array
Parameters:
id (array) : the array, an array of order block data declared using the UDT orderblock
OBshow (int) : the number of order blocks to show
BBshow (int) : the number of breaker blocks to show
OBcol (color) : color of order blocks
BBcol (color) : color of breaker blocks
bullishString (string) : the title of bullish blocks, which is a regular bullish orderblock or a bearish orderblock that's converted to breakerblock
bearishString (string) : the title of bearish blocks, which is a regular bearish orderblock or a bullish orderblock that's converted to breakerblock
isBullish (bool) : whether the array contains bullish orderblocks or bearish orderblocks. If bullish orderblocks,
the array will naturally contain bearish BB, and if bearish OB, the array will naturally contain bullish BB
labelLevels (string) : an input.string() to determine if labels for the block should be inside the box, outside, or none.
borderTransp (int)
liteMode (bool) : an input.bool(). True = neon effect, false = no neon.
rightCoordinate (int) : atime for the right coordinate of the box
masterCoords (map) : a map that stores the price of key levels and assigns them a name, used to determine price ranges
Returns: void
FVG
UDT for FVG calcualtions
Fields:
H (series float) : high price of user-selected timeframe
L (series float) : low price of user-selected timeframe
direction (series string) : FVG direction => "Up" or "Down"
T (series int) : => time of bar on user-selected timeframe where FVG was created
fvgLabel (series label) : optional label for FVG
fvgLineTop (series line) : optional line for top of FVG
fvgLineBot (series line) : optional line for bottom of FVG
fvgBox (series box) : optional box for FVG
labelLine
quickly pair a line and label together as UDT
Fields:
lin (series line) : Line you wish to pair with label
lab (series label) : Label you wish to pair with line
orderBlock
UDT for order block calculations
Fields:
orderBlockData (array) : array containing order block x and y points
orderBlockBox (series box) : optional order block box
vioCount (series int) : = 0 violation count of the order block. 0 = Order Block, 1 = Breaker Block
traded (series bool)
status (series string) : = "OB" status == "OB" => Level is order block. status == "BB" => Level is breaker block.
orderBlockLab (series label) : options label for the order block / breaker block.
strongPoints
UDT for strong highs and strong lows
Fields:
price (series float) : price of the strong high or strong low
timeAtprice (series int) : time of the strong high or strong low
strongPointLabel (series label) : optional label for strong point
strongPointLine (series line) : optional line for strong point
overlayLine (series line) : optional lines for strong point to enhance visibility
overlayLine2 (series line) : optional lines for strong point to enhance visibility
displacement
UDT for dispacements
Fields:
highPrice (series float) : high price of displacement
lowPrice (series float) : low price of displacement
timeAtPrice (series int) : time of bar where displacement occurred
displacementBox (series box) : optional box to draw displacement
displacementLab (series label) : optional label for displacement
po3data
UDT for po3 calculations
Fields:
dHigh (series float) : higher timeframe high price
dLow (series float) : higher timeframe low price
dOpen (series float) : higher timeframe open price
dClose (series float) : higher timeframe close price
po3box (series box) : box to draw po3 candle body
po3line (array) : line array to draw po3 wicks
po3Labels (array) : label array to label price points of po3 candle
macros
UDT for session macros
Fields:
sessions (array) : Array of sessions, you can populate this array using the "quickTime" function located above "export macros".
prices (matrix) : Matrix of session data -> open, high, low, close, time
sessionTimes (array) : Array of session names. Pairs with array sessions.
sessionLines (matrix) : Optional array for sesion drawings.
OTEtimes
UDT for data storage and drawings associated with OTE strategy
Fields:
upTimes (array) : time of highest point before trade is taken
dnTimes (array) : time of lowest point before trade is taken
tpLineLong (series line) : line to mark tp level long
tpLabelLong (series label) : label to mark tp level long
slLineLong (series line) : line to mark sl level long
slLabelLong (series label) : label to mark sl level long
tpLineShort (series line) : line to mark tp level short
tpLabelShort (series label) : label to mark tp level short
slLineShort (series line) : line to mark sl level short
slLabelShort (series label) : label to mark sl level short
sweeps
UDT for data storage and drawings associated with liquidity sweeps
Fields:
upSweeps (matrix) : matrix containing liquidity sweep price points and time points for up sweeps
dnSweeps (matrix) : matrix containing liquidity sweep price points and time points for down sweeps
upSweepDrawings (array) : optional up sweep box array. Pair the size of this array with the rows or columns,
dnSweepDrawings (array) : optional up sweep box array. Pair the size of this array with the rows or columns,
raidExitDrawings
UDT for drawings associated with the Liquidity Raid Strategy
Fields:
tpLine (series line) : tp line for the liquidity raid entry
tpLabel (series label) : tp label for the liquidity raid entry
slLine (series line) : sl line for the liquidity raid entry
slLabel (series label) : sl label for the liquidity raid entry
m2022
UDT for data storage and drawings associated with the Model 2022 Strategy
Fields:
mTime (series int) : time of the FVG where entry limit order is placed
mIndex (series int) : array index of FVG where entry limit order is placed. This requires an array of FVG data, which is defined above.
mEntryDistance (series float) : the distance of the FVG to the 50% range. M2022 looks for the fvg closest to 50% mark of range.
mEntry (series float) : the entry price for the most eligible fvg
fvgHigh (series float) : the high point of the eligible fvg
fvgLow (series float) : the low point of the eligible fvg
longFVGentryBox (series box) : long FVG box, used to draw the eligible FVG
shortFVGentryBox (series box) : short FVG box, used to draw the eligible FVG
line50P (series line) : line used to mark 50% of the range
line100P (series line) : line used to mark 100% (top) of the range
line0P (series line) : line used to mark 0% (bottom) of the range
label50P (series label) : label used to mark 50% of the range
label100P (series label) : label used to mark 100% (top) of the range
label0P (series label) : label used to mark 0% (bottom) of the range
sweepData (array)
silverBullet
UDT for data storage and drawings associated with the Silver Bullet Strategy
Fields:
session (series bool)
sessionStr (series string) : name of the session for silver bullet
sessionBias (series string)
sessionHigh (series float) : = high high of session // use math.max(silverBullet.sessionHigh, high)
sessionLow (series float) : = low low of session // use math.min(silverBullet.sessionLow, low)
sessionFVG (series float) : if applicable, the FVG created during the session
sessionFVGdraw (series box) : if applicable, draw the FVG created during the session
traded (series bool)
tp (series float) : tp of trade entered at the session FVG
sl (series float) : sl of trade entered at the session FVG
sessionDraw (series box) : optional draw session with box
sessionDrawLabel (series label) : optional label session with label
silverBulletDrawings
UDT for trade exit drawings associated with the Silver Bullet Strategy
Fields:
tpLine (series line) : tp line drawing for strategy
tpLabel (series label) : tp label drawing for strategy
slLine (series line) : sl line drawing for strategy
slLabel (series label) : sl label drawing for strategy
unicornModel
UDT for data storage and drawings associated with the Unicorn Model Strategy
Fields:
hPoint (chart.point)
hPoint2 (chart.point)
hPoint3 (chart.point)
breakerBlock (series box) : used to draw the breaker block required for the Unicorn Model
FVG (series box) : used to draw the FVG required for the Unicorn model
topBlock (series float) : price of top of breaker block, can be used to detail trade entry
botBlock (series float) : price of bottom of breaker block, can be used to detail trade entry
startBlock (series int) : start time of the breaker block, used to set the "left = " param for the box
includes (array) : used to store the time of the breaker block, or FVG, or the chart point sequence that setup the Unicorn Model.
entry (series float) : // eligible entry price, for longs"math.max(topBlock, FVG.get_top())",
tpLine (series line) : optional line to mark PT
tpLabel (series label) : optional label to mark PT
slLine (series line) : optional line to mark SL
slLabel (series label) : optional label to mark SL
rejectionBlocks
UDT for data storage and drawings associated with rejection blocks
Fields:
rejectionPoint (chart.point)
bodyPrice (series float) : candle body price closest to the rejection point, for "Up" rejections => math.max(open, close),
rejectionBox (series box) : optional box drawing of the rejection block
rejectionLabel (series label) : optional label for the rejection block
equalLevelsDraw
UDT for data storage and drawings associated with equal highs / equal lows
Fields:
connector (series line) : single line placed at the first high or low, y = avgerage of distinguished equal highs/lows
connectorLab (series label) : optional label to be placed at the highs or lows
levels (array) : array containing the equal highs or lows prices
times (array) : array containing the equal highs or lows individual times
startTime (series int) : the time of the first high or low that forms a sequence of equal highs or lows
radiate (array) : options label to "radiate" the label in connector lab. Can be used for anything
necessaryData
UDT for data storage of historical price points.
Fields:
highArr (array) : array containing historical high points
lowArr (array) : array containing historical low points
timeArr (array) : array containing historical time points
logArr (array) : array containing historical log returns
signArr (array) : array containing historical price directions
closeArr (array) : array containing historical close points
binaryTimeArr (array) : array containing historical time points, uses "push" instead of "unshift" to allow for binary search
binaryCloseArr (array) : array containing historical close points, uses "push" instead of "unshift" to allow the correct
binaryOpenArr (array) : array containing historical optn points, uses "push" instead of "unshift" to allow the correct
atrTFarr (array) : array containing historical user-selected TF atr points
openArr (array) : array containing historical open points
Smart Market Structure and Swing Points, version 1.0Smart Market Structure and Swing Points, Version 1.0
Overview
The Smart Market Structure and Swing Points script is designed to provide advanced insights into market structure and key swing points. This script helps identify important highs and lows, trend direction changes (structure breaks), and swing points, enhancing decision-making for both trend-following and reversal strategies. See below for detail presentation and why it has unique features.
Unique Features of the New Script
Market Structure Identification : Analyzes and marks key highs and lows to determine market structure, including higher highs, lower highs, higher lows, and lower lows.
Customizable Detection Length : Allows users to set the length for detecting highs and lows, providing flexibility to adapt to different market conditions and timeframes. Default value is 5 bars, but can be changed if needed.
Visual Signal Indicators (Labels) : Plots labels on the chart to indicate higher highs (HH), lower highs (LH), higher lows (HL), and lower lows (LL), along with corresponding RSI values, offering clear visual cues for market structure analysis. The indication of RSI values directly on high and low points enables to better judge whether the points are strong references (extreme RSI values) or weak references (middle RSI values)
Dynamic Trend Lines : Draws solid and dotted lines to connect significant highs and lows, visually representing the current trend direction and potential trend changes. Dashed lines indicates structure breaks.
Swing High and Swing Low Detection : Identifies and marks the most recent swing highs and swing lows, helping traders spot potential reversal points and key levels for setting stop losses or take profit targets .
Originality and Usefulness
This script combines market structure, trend breaks and RSI to provide a more robust view of market dynamic by indicating the strength or weakness of swing points , in that way the script is unique.
Signal Description
The script includes various signal features that highlight potential trading opportunities based on market structure:
Higher Highs (HH) and Higher Lows (HL) : These labels are plotted when new highs or lows are formed, indicating a continuation of an uptrend. The labels are positioned with consideration of the Average True Range (ATR) for better visibility.
Lower Highs (LH) and Lower Lows (LL) : These labels are plotted when new highs or lows are formed, indicating a continuation of a downtrend. The labels include RSI values to provide additional information on the strength or weakness of the points.
Trend Direction Change : Dotted lines are drawn to indicate potential trend direction changes when the script detects significant shifts in market structure.
Swing Highs and Swing Lows : These are identified based on a customizable swing length, marking recent significant highs and lows to highlight potential reversal points.
These signals help identify high-probability turning points and confirm trend direction by ensuring that the market structure aligns with the trading strategy.
Detailed Description
Input Variables
Length for High/Low Detection (`length`) : Defines the range to check for highs and lows. Default is 5.
RSI Length (`rsilength`) : The number of periods to calculate the RSI. Default is 14.
Functionality
Market Structure Calculation : The script determines the highest high and lowest low within the specified range to identify key points in market structure.
```pine
h = ta.highest(high, length * 2 + 1)
l = ta.lowest(low, length * 2 + 1)
```
Directional Logic : Variables and functions manage the state of the indicator, updating highs and lows based on the current trend direction.
```pine
var bool dirUp = false
var float lastLow = high * 100
var float lastHigh = 0.0
// Additional variables for tracking state
```
Drawing Lines and Labels : Functions draw lines and labels on the chart to visualize market structure and trend changes.
```pine
f_drawLine() =>
_li_color = dirUp ? color.red : color.lime
line.new(x1=timeHigh - length, y1=lastHigh, x2=timeLow - length, y2=lastLow, color=_li_color, width=3, style=line.style_solid, xloc=xloc.bar_index)
f_drawLastLine() =>
_li_color = dirUp ? color.blue : color.blue
if timeHigh > timeLow
line.new(x1=timeHigh - length, y1=lastHigh, x2=bar_index, y2=low, color=_li_color, width=2, style=line.style_dotted, xloc=xloc.bar_index)
else
line.new(x1=timeLow - length, y1=lastLow, x2=bar_index, y2=high, color=_li_color, width=2, style=line.style_dotted, xloc=xloc.bar_index)
```
Updating Highs and Lows : The main logic updates highs and lows based on the current trend direction, adding labels for new higher highs, lower highs, higher lows, and lower lows.
```pine
if dirUp
if f_isMin(length)
lastLow := low
// Additional logic for updating lows and labels
if f_isMax(length) and high > lastLow
lastHigh := high
// Additional logic for updating highs and labels
dirUp := false
li := f_drawLine()
```
Swing Highs and Lows : The script identifies recent swing highs and swing lows based on a customizable swing length, drawing lines to mark these points.
```pine
swingLength = 3 * length
isSwingHigh = ta.highestbars(high, swingLength) == 0
isSwingLow = ta.lowestbars(low, swingLength) == 0
if (isSwingHigh)
if (na(highLine))
highLine := line.new(bar_index, high, bar_index, high, color=color.green, style=line.style_solid, width=1)
else
line.set_xy1(highLine, bar_index, high)
line.set_xy2(highLine, bar_index + swingLength, high)
if (isSwingLow)
if (na(lowLine))
lowLine := line.new(bar_index, low, bar_index, low, color=color.red, style=line.style_solid, width=1)
else
line.set_xy1(lowLine, bar_index, low)
line.set_xy2(lowLine, bar_index + swingLength, low)
```
How to Use
Configuring Inputs : Adjust the detection length and RSI length as needed. Modify the lookback periods to suit your trading strategy. The indicator is adaptable and can be used on any timeframe.
Interpreting the Indicator : Use the labels and lines to gauge market structure and trend direction. Look for higher highs, lower highs, higher lows, and lower lows to confirm market structure.
Signal Confirmation : Pay attention to the labels and lines that provide signals for potential trend changes and swing points. Use these signals to better time entries and exits.
This script provides a detailed view of market structure and swing points, helping make more informed decisions by considering key highs and lows, trend direction changes, and the strength or weakness of swing points.